/*
 * @Author: NJ_1098 xiabaoxin
 * @Date: 2025-02-11 15:27:14
 * @LastEditors: NJ_1098 xiabaoxin
 * @LastEditTime: 2025-02-14 14:21:52
 * @Description: 通用工具
 */
const CryptoJs = require("crypto-js");
const { SCRIPT_KEY, IV_PARAMS } = require("../config/config.default");

class CommonUtils {
  /**
   * 生成UUID
   * @param {*} length 长度
   * @param {*} radix 基数
   * @returns
   */
  static UUID(length, radix) {
    let chars =
      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
    let uuid = [],
      i;
    radix = radix || chars.length;
    if (length) {
      for (i = 0; i < length; i++) uuid[i] = chars[0 | (Math.random() * radix)];
    } else {
      let r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
      uuid[14] = "4";
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | (Math.random() * 16);
          uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join("");
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 加密
   * @param {*} value
   * @return {*}
   */
  static encrypt(value) {
    const key = CryptoJs.enc.Utf8.parse(SCRIPT_KEY); // 密钥
    const iv = CryptoJs.enc.Utf8.parse(IV_PARAMS); // 加密强度
    const result = CryptoJs.AES.encrypt(value, key, {
      iv: iv,
    }).toString();
    return result;
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 解密
   * @param {*} value
   * @return {*}
   */
  static decrypt(value) {
    const key = CryptoJs.enc.Utf8.parse(SCRIPT_KEY); // 密钥
    const iv = CryptoJs.enc.Utf8.parse(IV_PARAMS); // 加密强度
    const result = CryptoJs.AES.decrypt(value, key, {
      iv: iv,
    }).toString(CryptoJs.enc.Utf8);
    return result;
  }
}

module.exports = CommonUtils;
